<template>
  <div>
    <div
      class="materialAdd"
      v-loading="detailInfoShow"
      v-if="!selectionMaterialShow"
      v-bind="$attrs"
    >
      <!-- 筛选按钮 -->
      <div class="search-button">

        <el-button
            v-if="pageType === 'check' "
            class="btn save"
     
            ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
            >同意</el-button
          >
        
        
        
        <el-button
          v-if="pageType !== 'detail' && pageType !== 'check'"
          class="btn save"
          @click="handleAddSave(materialFormRef)"
          ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
          >保存</el-button
        >
        <el-button
          class="btn submit"
          @click.stop="handleMaterial"
          v-if="pageType == 'add'"
          ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
          >选择物料</el-button
        >
        <el-button class="btn direction" @click="handleBack"
          ><el-icon class="icon" color="#fff"> <Back /> </el-icon
          >返回</el-button
        >
      </div>
      <el-collapse v-model="activeNames">
        <!-- 基础信息 -->
        <el-collapse-item name="1" class="transform-down">
          <template #title>
            <span class="circle"></span>
            <span class="collapse-title"
              >{{
                pageType !== "detail"
                  ? pageType === "add"
                    ? "新增"
                    : "编辑"
                  : ""
              }}评估产品</span
            >
          </template>
          <div class="material-info">
            <el-form
              :model="materialForm"
              ref="materialFormRef"
              :rules="queryRules"
              label-width="120"
              v-enterToNext
              :disabled="pageType === 'detail'"
            >
              <el-row>
                <el-col :span="6">
                  <el-form-item
                    label="选择物料:"
                    prop="materialName"
                    @click="handleMaterial"
                  >
                    <el-input
                      v-model="materialForm.materialName"
                      placeholder="选择物料后带入"
                      clearable
                      class="search-input"
                      disabled
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="物料分类:" prop="categoryName">
                    <el-input
                      ref="refInput"
                      v-model="materialForm.categoryName"
                      placeholder="选择物料后带入"
                      clearable
                      maxlength="20"
                      disabled
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="物料参数:" prop="technologyParameter">
                    <el-input
                      v-model="materialForm.materialParameter"
                      placeholder="选择物料后带入"
                      clearable
                      maxlength="80"
                      style="width: 1000px"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="适用/已用场景:" prop="applicableScene">
                    <el-input
                      style="width: 100%"
                      v-model="materialForm.applicableScene"
                      type="textarea"
                      maxlength="2000"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="备注:" prop="remark">
                    <el-input
                      style="width: 100%"
                      v-model="materialForm.remark"
                      type="textarea"
                      maxlength="2000"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="产品技术文档:">
                    <Upload
                      :fileList="materialForm.technicalFile"
                      :isFull="true"
                      :isCanDelete="pageType == 'detail' ? false : true"
                      :disabled="pageType == 'detail'"
                      :showButton="true"
                      :limit="10"
                      accept=".doc,.docx,.pdf,.jpg,.png"
                      @success="(result) => uploadSuccess(result, 1)"
                      @deleteFile="(result) => uploadRemove(result, 1)"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="售前方案典型:">
                    <Upload
                      :fileList="materialForm.planFile"
                      :isFull="true"
                      :isCanDelete="pageType == 'detail' ? false : true"
                      :disabled="pageType == 'detail'"
                      :showButton="true"
                      :limit="10"
                      accept=".doc,.docx,.pdf,.jpg,.png"
                      @success="(result) => uploadSuccess(result, 2)"
                      @deleteFile="(result) => uploadRemove(result, 2)"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
    <SelectionMaterial
      ref="selectionMaterialRef"
      v-if="selectionMaterialShow"
      v-model:selectionMaterialShow="selectionMaterialShow"
      @submitChoose="handleSelectMaterial"
    />
  </div>
</template>

<script setup>
import Upload from "@/components/Upload/index";
import SelectionMaterial from "./selectionMaterial";
import { getDictsApi } from "@/api/dict";
import { deptTreeSelect } from "@/api/system/user";
const { proxy } = getCurrentInstance();
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getproductmodifyApi,
  getcheckproductApi,
  getcheckproductdetailApi,
} from "@/api/operation/productEstimate.js";
const emit = defineEmits([
  // 刷新父组件表格数据
  "refreshList",
]);
const props = defineProps({
  // 操作类型
  pageType: {
    type: String,
    default: "add",
  },
  FormTemplate: {
    type: Object,
    default: {
      technicalFile: [],
      planFile: [],
    },
  },
});
// 折叠栏默认展开
const activeNames = ref(["1", "2", "3"]);
// 物料表单引用
const materialFormRef = ref();
// 详情加载效果
const detailInfoShow = ref(false);
// 输入框引用
const refInput = ref();
// 单位列表
const unitList = ref([]);
// 存货类型列表
const stockTypeList = ref([]);
// 供应商列表
const suppliereList = ref([]);
// 默认税率列表
const taxRateList = ref([]);
// 销售单价初始值
const purchasePrice = ref(null);
// 部门列表
const deptOptions = ref(undefined);
// 选择物料显隐
const selectionMaterialShow = ref(false);

// 物料表单数据模板
const materialFormTemplate = {
  technicalFile: [],
  planFile: [],
};
const data = reactive({
  // 物料表单
  materialForm: JSON.parse(JSON.stringify(materialFormTemplate)),
  // 物料表单校验规则
  queryRules: {
    materialName: [{ required: true, message: "请选择物料", trigger: "blur" }],
    categoryName: [{ required: true, message: "请选择物料", trigger: "blur" }],
    applicableScene: [
      { max: 79, message: "最大可输入80字符", trigger: "blur" },
    ],
    remark: [{ max: 79, message: "最大可输入80字符", trigger: "blur" }],
  },

  flagList: [
    {
      label: "是",
      value: 1,
    },
    {
      label: "否",
      value: 0,
    },
  ],
});
const { materialForm, queryRules, flagList } = toRefs(data);


watch(
  () => props.FormTemplate,
  (newValue, oldValue) => {
    materialForm.value = JSON.parse(JSON.stringify(newValue));
  },
  { deep: true }
);

/**
 * @description: 保存
 * @param {Object} materialFormRef 物料表单引用
 */
const handleAddSave = async (materialFormRef) => {
  if (!materialFormRef) return;
  await materialFormRef.validate(async (valid, fields) => {
    if (valid) {
      ElMessageBox.confirm("确定保存以上数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
      })
        .then(async () => {
          if (!materialForm.value.categoryName) {
            ElMessage.error("请先选择物料！");
            return;
          }
          materialForm.value.status = 0;
          const res = await getproductmodifyApi(materialForm.value);
          if (res.code === 200) {
            emit("update:productEstimateAddShow", false);
            emit("refreshList", true);
            ElMessage.success(res.msg);
            materialForm.value = JSON.parse(
              JSON.stringify(materialFormTemplate)
            );
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
    } else {
      console.log("error submit!");
    }
  });
};
/**
 * @description: 文件上传成功处理
 * @param {Object} response 文件信息
 */
function uploadSuccess(response, type) {
  switch (type) {
    case 1:
      materialForm.value.technicalFile.push({ ...response });
      break;
    case 2:
      materialForm.value.planFile.push({ ...response });
      break;
    default:
      break;
  }
}

/**
 * @description: 删除文件
 * @param {Number} index 当前文件索引
 */
function uploadRemove(index, type) {
  switch (type) {
    case 1:
      materialForm.value.technicalFile.splice(index, 1);
      break;
    case 2:
      materialForm.value.planFile.splice(index, 1);
      break;
    default:
      break;
  }
}

/**
 * @description: 返回
 */
const handleBack = () => {
  if (props.pageType === "detail") {
    emit("update:productEstimateAddShow", false);
    materialForm.value = JSON.parse(JSON.stringify(materialFormTemplate));
  } else {
    ElMessageBox.confirm("确定返回上一级吗?以上数据未保存将会丢失!", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      confirmButtonClass: "confirmBtnClass",
      cancelButtonClass: "cancelBtnClass",
    })
      .then(async () => {
        emit("update:productEstimateAddShow", false);
        materialForm.value = JSON.parse(JSON.stringify(materialFormTemplate));
      })
      .catch(() => {});
  }
};

/**
 * @description: 获取字典
 */
async function getDicts() {
  // 部门列表
  await deptTreeSelect().then((response) => {
    deptOptions.value = response.data;
  });
}
/**
 * @description: 处理选择物料
 */
const addType = ref("");
const handleMaterial = () => {
  addType.value = "select";
  selectionMaterialShow.value = true;
};
/**
 * @description: 处理物料选择
 */
const handleSelectMaterial = (value) => {
  if (value) {
    selectionMaterialShow.value = false;
    materialForm.value.materialName = value.materialName;
    materialForm.value.materialId = value.materialId;
    materialForm.value.categoryName = value.categoryName;
    materialForm.value.categoryId = value.categoryId;
    materialForm.value.materialParameter = value.technologyParameter;
  } else {
    ElMessage.info("请选择物料");
  }
};
/**
 * @description: 处理编辑信息
 * @param {Number} id
 */
const handleEditInfo = async (id) => {
  try {
    detailInfoShow.value = true;
    const res = await getcheckproductdetailApi(id);
    materialForm.value = res.data;
    detailInfoShow.value = false;
  } catch (error) {
    detailInfoShow.value = false;
  }
};

/**
 * @description: 处理供应商、生产厂家选择
 */
const handleSuppliereSelect = (value, type) => {
  switch (type) {
    case 1:
      materialForm.value.supplierId = value.supplierId;
      break;
    case 2:
      materialForm.value.manufacturerId = value.supplierId;
      break;
    default:
      break;
  }
};

onMounted(() => {
  getDicts();
  nextTick(() => {
    refInput.value.focus(); // 聚焦
  });
});

const querySearch = (queryString, cb) => {
  const results = queryString
    ? suppliereList.value.filter(createFilter(queryString))
    : suppliereList.value;
  cb(results);
};
const createFilter = (queryString) => {
  return (restaurant) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    );
  };
};

defineExpose({
  handleEditInfo,
});
</script>
<style>
.autocomplete-item.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>
<style lang="scss" scoped>
.materialAdd {
  padding: 20px 20px;
  width: 100%;
  height: 100%;
  .el-collapse,
  .el-collapse-item__wrap {
    border: none;
  }

  .search-input {
    width: 268px;
    height: 34px;
  }
  .material-info {
    padding: 20px 10px 5px 10px;
    background-color: #fafafa;
    margin: 10px 0;
  }
  .contact-info {
    padding-top: 20px;
    .table-operate {
      display: flex;
      justify-content: space-around;
      .table-icon {
        width: 20px;
        height: 20px;
        cursor: pointer;
      }
    }
  }
}
.auto-top {
  width: 100%;
  position: absolute;
  top: 0px;
  display: flex;
  font-weight: bold;
}
.auto-item {
  width: 125px;
  text-align: center;
  white-space: nowrap; /* 禁止换行 */
  overflow: hidden; /* 隐藏超出部分 */
  text-overflow: ellipsis; /* 使用省略号表示超出部分 */
}
.el-autocomplete .el-autocomplete-suggestion {
  max-height: 200px; /* 设置最大高度 */
  overflow-y: auto; /* 超出高度时显示滚动条 */
}
</style>
